package com.cqc.jdk8.Jutil.stream;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class FilterTest {


    List<String> stringList = null;

    @Before
    public void before() {
        stringList = getStringList();
    }

    @Test
    public void f1() {
        stringList.stream()
                .filter((str) -> str.startsWith("a"))
                .forEach(System.out::println);
        //相当于
        stringList.stream()
                .filter(new Predicate<String>() {
                    @Override
                    public boolean test(String s) {
                        return s.startsWith("a");
                    }
                })
                .forEach(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        System.out.println(s);
                    }
                });
//        aaa2,aaa1
    }

    @Test
    public void f2() {
        //如果筛选不到，结果是 new ArrayList()
        List<String> list = stringList.stream()
                .filter(s -> s.startsWith("ax"))
                .collect(Collectors.toList());
        System.out.println(list);
    }


    private static List<String> getStringList() {
        List<String> strList = new ArrayList<>();
        strList.add("a1");
        strList.add("a2");
        strList.add("b1");
        strList.add("b2");
        strList.add("b3");
        strList.add("c1");
        strList.add("d1");
        strList.add("d2");
        return strList;
    }

}
